/*
 * @lc app=leetcode.cn id=113 lang=javascript
 *
 * [113] 路径总和 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number[][]}
 */
var pathSum = function (root, targetSum) {
  const res = []
  if (root === null) {
    return res
  }
  const queque = [root]
  const paths=[[]]
  while (queque.length) {
    const node = queque.shift()
    let path = paths.shift()
    path.push(node.val)
    if (node.left === null && node.right === null) {
      const sum = path.reduce((pre, cur) => pre += cur, 0)
      if (sum === targetSum) {
        res.push(path)
        continue
      }
    }
    if (node.left) {
      queque.push(node.left)
      paths.push([...path])
    }
    if (node.right) {
      queque.push(node.right)
      paths.push([...path])
    }
  }
 return res
};
// @lc code=end

